//initContainerHeight();
CURRENT_PAGE = 1;
TEMPLATE_SELF = '';
TEMPLATE_OTHER = '';
CHAT_OBJ = {};
MSG_OR_OFFER = 'offer';
CURRENT_AUCTION_GOODS = {id:0};
CURRENT_NUM = 0;
CURRENT_PRICE = 100;
PRICE_GAP = 10;
IS_OVER = false;
IS_HOST = false;
HAVE_BEGUN = 2;
COUNT_DOWN_ING = false;

$(function(){
	initData();
	//renderGrade();//一期不开发专场，会员等级
	loadNextAuctionGoods();
	initEvent();
	initChat();
});

function initData(){
	if(!lh.param)lh.param = {};
	lh.current.num = 0;
	if(!lh.param.ap){//拍卖为空，直接跳转到专场首页
		//lh.jumpR('/ap/inst');return;
	}
	if(!lh.param.ap.haveBegun)lh.param.ap.haveBegun = 1;//开始状态
	if(lh.param.host){//主持人登陆
		lh.param.host = true;
		switchMsgOffer('msg');//主持人不能出价，切换到发言状态
		$('#hostCountdown').show();
		//if(!lh.param.userCount)lh.param.userCount = 0;//在线人数
		//$('#onlineUser').text('（在线：'+userCount+'人）').show();
	}
}

/*function renderGrade(){
	var grade = $('#instGrade').val();
	var gradeDom = '';
	if(grade && grade > 100){
		var grade = grade.toString();
		var diamond = grade[1];
		var star = grade[2];
		for(var j = 0;j<star;j++){
			gradeDom += '<img src="/images/front/sale_img2.png" width="12" height:"12" class="mgH1 fr" style="padding-top:2px;"/>';
		}
		for(var i = 0;i<diamond;i++){
			gradeDom += '<img src="/images/front/diamond_blue.png" width="15" height:"15" class="fr" style="padding-top:1px;"/>';
		}
	}
	$('#grade').append(gradeDom);
}*/

/** 加载拍卖藏品 */
function loadNextAuctionGoods(){
	var auctionId = lh.param.auctionId;
	if(!auctionId){
		//lh.jumpR('/ap/inst');return;
	}
	lh.post('front', '/ap/hall/getNextAuctionGoods',{auctionId : auctionId}, function(rsp){
		if(rsp.success){
			lh.param.haveBegun = rsp.haveBegun;
			var haveBegun = lh.param.haveBegun; 
			if(haveBegun == 1){//拍卖预展 
				auctionPreCheck(auctionId);// 定时检查拍卖是否开始
			}else if(haveBegun == 2){//拍卖中
				var seconds = rsp.remainSeconds;
				refreshTimmer(seconds);//成功加载拍品后就刷新倒计时
				countdownWithMask(auctionOneDone);//开始倒计时
			}else if(haveBegun == 3){//拍卖结束
				auctionOver();
			}
			lh.current.num ++;//当前是第几个拍品
			var auctionGoods = rsp.auctionGoods;
			lh.current.ag = auctionGoods
			lh.current.ag.total = rsp.total;
			lh.current.ag.remain = rsp.remain;
			lh.current.ag.deal = rsp.deal;
			lh.current.ag.price = parseInt( auctionGoods.offerPrice || auctionGoods.priceBegin );
			lh.current.ag.priceGap = 10;//TODO 暂时定为10元，应根据数据定义的加价金额
			freshGoodsDom();
		}else if(rsp.code == 'auction_over'){//拍卖结束
			lh.current.ag = null;
			auctionOver();
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

/** 拍卖结束，返回专场首页 */
function auctionOver(){
	$('#have_begun_text').val('结束');
	var msgContent = '本次拍卖已经结束，感谢大家的参与。'
	sendSystemMsg({remote:false, content:msgContent, group:'msg_over', senderName:'主持人'});
	lh.param.isOver = true;
	setTimeout(function(){
		//lh.jumpR('/ap/auctions');return;
	},5000);
}

/** 拍卖状态为预展时，定期检查是否开拍 */
function auctionPreCheck(auctionId){
	setTimeout(function(){
		lh.post('front', '/ap/hall/getProfessionHaveBegun', {auctionId : auctionId}, function(rsp){
			if(rsp.success){
				var haveBegun = rsp.haveBegun;
				lh.param.haveBegun = haveBegun;
				if(haveBegun == 1){//仍处于预展状态，继续定期检查
					auctionPreCheck(auctionId);
				}else if(haveBegun == 2){//拍卖开始
					$('#haveBegun').val(2);
					$('#have_begun_text').text('拍卖中');
					lh.alert('拍卖开始了，大家开始竞价吧。');
					loadNextAuctionGoods();
				}if(haveBegun == 3){//拍卖结束
					auctionOver();
				}
			}
		}, 'json');
	},15000);//15秒
}

/** 成功加载拍品信息后，更新页面信息 */
function freshGoodsDom(){
	if(!lh.current.ag.offerTimes)lh.current.ag.offerTimes = 0;
	var goods = lh.current.ag;
	$('#goodsRemain').text(goods.remain);
	$('#goodsDeal').text(goods.deal);
	$('#goodsTotal').text(goods.total);
	if(goods.picPath)$('#picPath').attr('src', buildOSSZoomByPath(goods.picPath, 115, 115) );
	$('#goodsName').text(goods.goodsName);
	$('#currentNum').text(lh.current.num);
	var s = goods.goodsSerial;
	if(s){
		//$('#goodsSerial').text(s);
		$('#goodsSerial').text(goods.id);//TODO 直接使用auctionGoods的ID作为编号
		$('#serialSpan').show();
	}else{
		$('#serialSpan').hide();
	}
	$('#priceBegin').text(goods.priceBegin || 1);
	$('#currentPrice').text(lh.current.ag.price || 1);
	$('#currentUser').text(goods.offerUsername || '暂无');
	$('#offerTimes').text(goods.offerTimes || 0);
	$('#offerPrice').val(lh.current.ag.price + lh.current.ag.priceGap);
	if(lh.param.haveBegun == 2){//在拍卖中时才发拍品描述
		lh.current.ag.msgPrefix = "第"+lh.current.num+"件拍品："+goods.goodsName+"。   ";
		var content = lh.current.ag.msgPrefix + goods.goodsDescription;
		sendSystemMsg({remote:false, content:content, group:'msg_host', senderName:'主持人'});
		sendSystemMsg({remote:false, content:"大家开始出价吧", group:'msg_host', senderName:'主持人'});
		//sendGoodsPic();
	}
}

function initEvent(){
    $('#pf_host_cha').click(function () {
        $('#t_0100_17').hide();
        $(this).hide();
        $('#pf_host_cha2').show();
        initHallHeight();
    });
    $('#pf_host_cha2').click(function () {
        $('#t_0100_17').show();
        $(this).hide();
        $('#pf_host_cha').show();
        initHallHeight();
    });
}

/** 切换状态：出价，发言 */
function switchMsgOffer(operation){
	if(operation == 'offer'){
		if(lh.param.isHost){
			lh.alert('您是本拍场的主持人，不能参与竞价');return;
		}
		lh.param.msgOrOffer = 'offer';
		$('#host_write').show();
		$('#host_sub').hide();
	}else{
		lh.param.msgOrOffer = 'msg';
		$('#host_sub').show();
		$('#host_write').hide();
	}
}

/** 更新默认出价金额 */
function changePrice(operation){
	var offerPrice = $('#offerPrice').val();
	if(!offerPrice || !$.isNumeric(offerPrice))offerPrice = lh.current.ag.price;
	offerPrice = parseInt(offerPrice);
	if(operation == 'add'){
		offerPrice = offerPrice + lh.current.ag.priceGap;
	}else if(operation == 'del'){
		offerPrice = offerPrice - lh.current.ag.priceGap;
	}
	if(offerPrice <= lh.current.ag.price){
		offerPrice = lh.current.ag.price + lh.current.ag.priceGap;
		lh.alert('不能低于当前出价');
	}
	$('#offerPrice').val(offerPrice);
	return offerPrice;
}

/** 更新出价增加幅度 */
function changePriceGap(){
	if(CURRENT_PRICE <= 50){
		lh.current.ag.priceGap = 10;
	}else if(CURRENT_PRICE < 400){
		lh.current.ag.priceGap = 20;
	}else if(CURRENT_PRICE < 1000){
		lh.current.ag.priceGap = 50;
	}else{
		lh.current.ag.priceGap = 100;
	}
}

function initChat(){
	var chatGroupId = lh.param.ap.chatGroupId;
	var userTokenId = lh.param.userTokenId;
	var userTokenPswd = lh.param.userTokenPswd;
	var chatSig = lh.param.sig;
	var chatTimeStamp = lh.param.timeStamp;
	var senderId = lh.param.senderId;
	var senderAvatar = lh.param.senderAvatar;
	var senderName = lh.param.senderName;
	var senderSerial = lh.param.senderSerial;

	/*var receiverTokenId = $('#receiverTokenId').val();
	var receiverId = $('#receiverId').val();
	var receiverAvatar = $('#receiverAvatar').val();
	var receiverName = $('#receiverName').val();*/
	
	lh.current.chatObj = {
		userTokenId:userTokenId,
		userTokenPswd:userTokenPswd,
		chatSig:chatSig,
		chatTimeStamp:chatTimeStamp,
		senderId:senderId,
		senderAvatar:senderAvatar,
		senderName:senderName,
		chatGroupId:chatGroupId,
		receiverId:chatGroupId,
		senderSerial:senderSerial
		/*receiverId:receiverId,
		receiverTokenId:receiverTokenId,
		receiverAvatar:receiverAvatar,
		receiverName:receiverName,*/
	};
	
	lh.plugins.templateSelf = $('#template_self').html();
	Mustache.parse(lh.plugins.templateSelf); 
	lh.plugins.templateOther = $('#template_other').html();
	Mustache.parse(lh.plugins.templateOther);
	lh.plugins.templateBonus = $('#template_bonus').html();
	Mustache.parse(lh.plugins.templateBonus);
	
	var options = {
		userTokenId:userTokenId,
		userTokenPswd:userTokenPswd,
		senderId:senderId,
		chatGroupId:chatGroupId,
		receiverId:chatGroupId,
		chatSig:chatSig,
		chatTimeStamp:chatTimeStamp,
		senderSerial:senderSerial
	}
	
	var onJoinGroupFun = function(){
		sendSystemMsg({remote:false, content:'欢迎'+senderName, group:'msg_welcome'});
	}
	var onLoginFun = function(){
		joinGroup(chatGroupId, onJoinGroupFun);
	}
	initCommonChat(options, onLoginFun, true);//isShowHour:true
}

function sendOffer(){
	if(!checkBail())return;//检查保证金
	if(lh.param.haveBegun == 1){
		lh.alert('本次拍卖正在预展中，请拍卖开始后开始竞价。');return;
	}
	if(lh.param.isOver || lh.param.haveBegun == 3){
		lh.alert('本次拍卖已经结束，感谢您的参与。');return;
	}
	var offerPrice = changePrice();
	lh.current.ag.price = offerPrice;
	var chat = _.cloneDeep(lh.current.chatObj);
	chat.content = '出价'+offerPrice+'元';
	chat.price = offerPrice;
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = lh.formatDate({format:'HH:mm:ss'});
	chat.msgGroup = 'msg_price';
	chat.auctionGoodsId = lh.current.ag.id;
	chat.localPrice = '出价<span style="color:green;"> '+offerPrice+'</span> 元';
	commonSendGroupMsg(chat);
	//修改最高价格和领先人
	changePriceGap();
	$('#currentPrice').text(offerPrice|| lh.current.ag.price);
	$('#currentUser').text(lh.param.username || '暂无');
	$('#offerPrice').val(offerPrice + lh.current.ag.priceGap);
	$('#offerTimes').text(++lh.current.ag.offerTimes);
	//更新数据库
	var param = {
		offerPrice:lh.current.ag.price, 
		offerTimes:lh.current.ag.offerTimes,
		id:lh.current.ag.id
	};
	updateAuctionGoods(param);
}

function goToBottom(){
	//竖向滚动条置顶(window.scrollTo(0,0);
	//竖向滚动条置底 window.scrollTo(0,document.body.scrollHeight)
	var h = document.body.scrollHeight;
	document.getElementById('body').scrollTop=h;
	//window.scrollTo(0, h);
}

function sendMsg(msgContent, notDB, sender, msgGroup){
	var chat = _.cloneDeep(lh.current.chatObj);
	chat.content = msgContent || $("#msgContent").val();
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = lh.formatDate({format:'HH:mm:ss'});
	chat.msgGroup = msgGroup || 'msg_common';//普通消息
	if(sender)chat.senderName = sender;
	if(lh.param.isHost){
		sendSystemMsg({remote:true, content:chat.content, group:'msg_host', senderName:'主持人'});
	}else{
		commonSendGroupMsg(chat, notDB);
	}
	hideChatTool();//消息发送后自动隐藏聊天工具栏
	goToBottom();
}

function sendSystemMsg(param){
	var isRemoteSend = param.remote;
	var msgContent = param.content;
	var msgGoodsPic = param.goodsPic;
	var msgGroup = param.group;
	var senderName = param.senderName;
	var bonus = param.bonus;
	if(msgGoodsPic && !msgContent)msgContent = '拍品图片展示：';
	if(!senderName)senderName = '系统';
	var sendHour = lh.formatDate({format:'HH:mm:ss'});
	if(isRemoteSend){
		var senderId = lh.param.senderId;
		var chat = {
			content:msgContent,
			goodsPic:msgGoodsPic,
			chatGroupId:lh.current.chatObj.chatGroupId,
			senderAvatar:null,
			avatar:null,
			senderName:senderName,
			senderId:senderId,
			msgGroup:msgGroup,
			sendHour:sendHour,
			localPrice:null,
			price:null,
			agId:null,
			bonus:bonus
		};
		commonSendGroupMsg(chat, false, false);//:chat,notDB,notAppend
	}else{
		var chat = {msgGroup:msgGroup, sendHour:sendHour, senderName:senderName, content:msgContent, goodsPic:msgGoodsPic};
		var rendered = Mustache.render(lh.plugins.templateSelf, {chat:chat});
		commonGroupAppend(rendered);
	}
	hideChatTool();//消息发送后自动隐藏聊天工具栏
}

//TODO 主持人开始倒计时
function sendGroupMsgCountDown(forceOver){//发出开始拍卖倒计时消息，不显示出来，只刷新倒计时时间
	if(lh.param.countDownIng || lh.param.timmer <= 15)return;
	lh.param.countDownIng = true;
	setRemainSeconds(lh.current.ag.id, forceOver);//更新倒计时
	var chat = _.cloneDeep(lh.current.chatObj);
	var senderId = $('#senderId').val();
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = lh.formatDate({format:'HH:mm:ss'});
	chat.msgGroup = 'count_down';//开始倒计时消息
	
	var chat = {
		content:'-sys-weipaike-countdown-begin-',
		chatGroupId:lh.current.chatObj.chatGroupId,
		senderAvatar:null,
		avatar:null,
		senderName:chat.senderName,
		senderId:senderId,
		msgGroup:chat.msgGroup,
		sendHour:chat.sendHour,
		localPrice:null,
		price:null,
		agId:lh.current.ag.id,
		bonus:null
	};
	commonSendGroupMsg(chat,true,true);//:chat,notDB,notAppend
	hideChatTool();//消息发送后自动隐藏聊天工具栏
}

function addPraise(id){
	var praiseNum = $("#praiseNum").val();
	praiseNum++;
	var obj = {};
	obj.praiseNum = praiseNum;
	obj.id = id;
	lh.post('front', '/ap/hall/addOrUpdateAuction',obj,function(rsp){
		if(rsp.success){
			$("#praise").text('已点赞');
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function updateAuctionGoods(param, isLoadNext){
	lh.post('front', '/ap/hall/updateAuctionGoods', param, function(rsp){
		if(rsp.success && rsp.remainSeconds){
			refreshTimmer(rsp.remainSeconds);
		}else{
			//提示用户流拍或成交
			if(rsp.code == 'already_done'){
				var content = '很遗憾没有人出价，展示下一个拍品';
				sendSystemMsg({remote:false, content:content, group:'msg_host', senderName:'主持人'});
			}else if(rsp.code == 'already_deal'){
				var content = '恭喜['+rsp.username+'] 成功拍下该拍品，展示下一个拍品';
				sendSystemMsg({remote:false, content:content, group:'msg_host', senderName:'主持人'});
			}
			if(isLoadNext){//没有返回成功状态，返回了流拍或已完成竞拍，就加载下一个
				loadNextAuctionGoods();//next
			}
			if(!param.notShowTip){
				lh.alert(rsp.msg);
			}
		}
		goToBottom();
	}, 'json');
}

function auctionOneDone(){
	var param = {
		id:lh.current.ag.id,
		done:1,
		notShowTip:1
	};
	updateAuctionGoods(param,true);
}

function getRemainSeconds(auctionGoodsId){
	lh.post('front', '/ap/hall/getRemainSeconds', {auctionGoodsId:auctionGoodsId}, function(rsp){
		if(rsp.success){
			if(rsp.agStatus){
				loadNextAuctionGoods();return;
			}
			var timmer = rsp.remainSeconds;
			if(!timmer || timmer < 0)timmer = 120;
			lh.param.timmer = timmer;
			//onlineUser
			/*if(lh.param.isHost){
				var userCount = rsp.userCount;
				if(!userCount)userCount = 0;
				$('#onlineUser').text('（在线：'+userCount+'人）').show();
			}*/
		}
	}, 'json');
}

function setRemainSeconds(auctionGoodsId, forceOver){
	var param = {auctionGoodsId:auctionGoodsId};
	if(forceOver)param.forceOver = forceOver;
	lh.post('front', '/ap/hall/setRemainSeconds', param, function(rsp){
		lh.param.countDownIng = false;
		if(rsp.success){
			getRemainSeconds(auctionGoodsId);//重新发请求，保证时间同步，减少误差
			//if(rsp.remainSeconds)TIMMER = rsp.remainSeconds;
		}
	}, 'json');
}

function addChat(chat){
	var param = {serial:chat.serial,chatGroupId:chat.chatGroupId,content:chat.content};
	lh.post('front', '/chat/addChatProfession',param,function(rsp){
		if(rsp.failure){
			lh.alert(rsp.msg);
		}
	},'json');
}

CHECKING_FLAG = false;
function sendBonus(){
	if(CHECKING_FLAG)return;
	CHECKING_FLAG = true;
	lh.post('front', '/checkBonusRemain', null, function(rsp){
		frontLoginCheck(rsp);//登陆检查
		CHECKING_FLAG = false;
		if(rsp.success){
			var username = rsp.username;
			var userId = rsp.userId;
			var msgContent = '['+username+'] 给大家发红包啦，点击这里抢红包。';
			sendSystemMsg({remote:true, content:msgContent, group:'msg_over', senderName:'主持人', bonus:userId});
		}else{
			if(rsp.code == 'bonus_lack'){
				jumpToBonus();return;
			}
			lh.alert(rsp.msg);
		}
	},'json');
}

function receiveBonus(senderId){
	var param = {bossId:senderId,isGroupBonus:1};
	lh.post('front', '/receiveBonus', param, function(rsp){
		frontLoginCheck(rsp);//登陆检查
		if(rsp.success){
			var username = rsp.username;
			var money = rsp.money;
			var bonusId = rsp.bonusId;
			if(!money || !bonusId){
				lh.alert('红包已经被抢光了');return;
			}
			lh.alert('恭喜您成功抢到一个红包，金额为：'+money+'元，您可在个人中心的红包菜单里面查看详细信息');
			var msgContent = '恭喜['+username+'] 成功抢到一个红包，金额为：'+money+'元';
			sendSystemMsg({remote:true, content:msgContent, group:'msg_over', senderName:'主持人'});
		}else{
			if(rsp.code == 'bonus_lack'){
				jumpToBonus();return;
			}
			lh.alert(rsp.msg);
		}
	},'json');
}

/** 发拍品描述 */
function sendGoodsDesc(){
	var content = '拍品编号：'+lh.current.ag.serial +'，'+lh.current.ag.goodsName+'，'
	+lh.current.ag.goodsDescription+'。起拍价'+ lh.current.ag.priceBegin+'元';
	sendSystemMsg({remote:true, content:content, group:'msg_host', senderName:'主持人'});
	goToBottom();
}

/** 发拍品图片 */
function sendGoodsPic(){
	var picPaths = lh.current.ag.picPaths;
	var picAry = _.split(picPaths, ',');
	//var pic = '<img src="/images/zy/pic/gs_pic1.jpg">';
	var pic = '</br>';
	_.forEach(picAry, function(value) {
		pic += '<img style="max-height:180px;padding: 5px;" src="'+buildOSSZoomByPath(value, 300, 300)+'">';
	});
	sendSystemMsg({remote:true, goodsPic:pic, group:'msg_host', senderName:'主持人'});
	goToBottom();
}

/** 叫场 */
function callCuation(){
	var content = '还有出价的吗？没有出价的就开始倒计时了';
	sendSystemMsg({remote:true, content:content, group:'msg_host', senderName:'主持人'});
	goToBottom();
}

/** 倒计时 */
function auctionCountdown(){
	sendGroupMsgCountDown();
	goToBottom();
}

/** 流拍 */
function auctionfallThrough(){
	var content = '展示下一件拍品';
	sendSystemMsg({remote:true, content:content, group:'msg_host', senderName:'主持人'});
	sendGroupMsgCountDown(1);
	goToBottom();
}


function transToMsgSend(){
	$("#msgContent").val($("#msgContent2").val());
	sendMsg();
}

function jumpToUserHome(serial){
	lh.alert('点击跳往用户主页，用户个人中心完成后更新此链接');return;
	lh.jumpR('/user/'+serial);
}